package xdu.ble.auth.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xdu.ble.auth.config.JwtProperties;
import xdu.ble.auth.service.AuthService;
import xdu.ble.common.enums.ExceptionCode;
import xdu.ble.common.exception.BLEException;
import xdu.ble.common.utils.CookieUtils;
import xdu.lz.auth.entity.UserInfo;
import xdu.lz.auth.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
@RequestMapping("auth/")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    @Value("${ble.jwt.cookieName}")
    private String cookieName;


    @Value("${ble.jwt.cookieMaxAge}")
    private int cookieMaxAge;

    private final Logger logger = LoggerFactory.getLogger(AuthController.class);

    /**
     * 登录授权
     *
     * @return
     */
    @RequestMapping("login")
    public ResponseEntity<Void> authentication(String phoneNum, String passWord,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
        // 登录校验
        String token = this.authService.authentication(phoneNum, passWord);
        logger.debug("token = " + token);
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, cookieName,
                token, cookieMaxAge, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户信息
     *
     * @param token
     * @return
     */
    @RequestMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("BLE_TOKEN") String token,
                                               HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取token信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            // 如果成功，我们还需要刷新token
            String newToken = JwtUtils.generateToken(userInfo,
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            // 然后写入cookie中
            // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request, response, cookieName,
                    newToken, cookieMaxAge, true);
            // 成功后直接返回
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            throw new BLEException(ExceptionCode.USER_NOT_LOGIN);
        }
    }

}
